//
//  FBHomeViewController.m
//  FindBook
//
//  Created by zhaoxu_liu on 13-11-1.
//  Copyright (c) 2013年 lzx. All rights reserved.
//

#import "FBHomeViewController.h"
#import "PETableView.h"
#import "FBBooksModel.h"
#import "FBBooksData.h"
#import "RYCHTTPImageView.h"

#import "FBDetailViewController.h"

@interface FBHomeViewController ()<UITableViewDataSource, PETableViewDelegate>
{
    PETableView *_tableView;
    NSArray *_tableViewData;
    FBBooksModel *_booksModel;
    
    NSString *_catalogID;
}

@end

@implementation FBHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _booksModel = [[FBBooksModel alloc] initWithDelegate:self];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNavigationBarButtonItemWithTitle:@"menu" bgImage:[UIImage imageNamed:@"navigationBtn_rightRect.png"] itemType:RYCNavigationbarButtonItem_Left useTitleWidth:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification:) name:FBLOADBOOKSNOTIFICATION object:nil];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_grayBg.png"]];
    bgImageView.frame = self.view.bounds;
    [self.view addSubview:bgImageView];
    
    [self showMenu];
    
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)navigationLeftButtonItemClicked:(id)aSender
{
    [self showMenu];
}


#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableViewData.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* reuseID = @"normalCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    if (nil == cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseID];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        
        CGFloat marginLeft = 15;
        CGFloat imageWidth = 102;
        CGFloat labelWidth = 320 - marginLeft * 4 - imageWidth;
        CGFloat imageHeight = 135;
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(marginLeft, 10, labelWidth, 25)];
        titleLabel.tag = 101;
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.font = [UIFont systemFontOfSize:16];
        [cell.contentView addSubview:titleLabel];
        
        UILabel *sub1Label = [[UILabel alloc] initWithFrame:CGRectMake(marginLeft, 32, labelWidth, 35)];
        sub1Label.tag = 102;
        sub1Label.backgroundColor = [UIColor clearColor];
        sub1Label.font = [UIFont systemFontOfSize:14];
        sub1Label.textColor = FBRGBA(0x6a,0x6a,0x6a,1);
        sub1Label.lineBreakMode = NSLineBreakByCharWrapping;
        sub1Label.numberOfLines = 2;
        [cell.contentView addSubview:sub1Label];
        
        UILabel *sub2Label = [[UILabel alloc] initWithFrame:CGRectMake(marginLeft, 70, labelWidth, 35)];
        sub2Label.tag = 103;
        sub2Label.backgroundColor = [UIColor clearColor];
        sub2Label.font = [UIFont systemFontOfSize:14];
        sub2Label.textColor = FBRGBA(0x6a,0x6a,0x6a,1);
        sub2Label.lineBreakMode = NSLineBreakByCharWrapping;
        sub2Label.numberOfLines = 2;
        [cell.contentView addSubview:sub2Label];
        
        UILabel *readingLabel = [[UILabel alloc] initWithFrame:CGRectMake(marginLeft, 127, labelWidth, 20)];
        readingLabel.tag = 104;
        readingLabel.backgroundColor = [UIColor clearColor];
        readingLabel.font = [UIFont systemFontOfSize:14];
        readingLabel.textColor = FBRGBA(0x6a,0x6a,0x6a,1);
        readingLabel.lineBreakMode = NSLineBreakByCharWrapping;
        readingLabel.numberOfLines = 2;
        [cell.contentView addSubview:readingLabel];
        
        RYCHTTPImageView *imageView = [[RYCHTTPImageView alloc] initWithFrame:CGRectMake(205, 10, imageWidth, imageHeight)];
        imageView.tag = 105;
        [cell.contentView addSubview:imageView];
        
    }
    
    FBBooksData *bookData = [_tableViewData objectAtIndex:indexPath.row];
    
    UILabel *titleLabel = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *sub1Label = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *sub2Label = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *readingLabel = (UILabel *)[cell.contentView viewWithTag:104];
    RYCHTTPImageView *imageView = (RYCHTTPImageView *)[cell.contentView viewWithTag:105];
    
    titleLabel.text = bookData.title;
    sub1Label.text = bookData.sub1;
    sub2Label.text = bookData.sub2;
    readingLabel.text = bookData.reading;
    
    NSURL *imageURL = [NSURL URLWithString:bookData.img];
    [imageView setURLImage:imageURL imageQueue:self.httpImageQueue];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 155;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FBDetailViewController *detailViewController = [[FBDetailViewController alloc] init];
    detailViewController.bookData = [_tableViewData objectAtIndex:indexPath.row];
    
    [self.navigationController pushViewController:detailViewController animated:YES];
}

#pragma mark UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
	[_tableView didScroll];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	[_tableView didEndDragging];
}

#pragma mark - PETableViewDelegate
- (void)didReloadTableViewDataSource:(PETableView*)tableView
{
    [self requestBooksWithOperation:RYCHTTPRequestModelOperation_Refresh];
}

- (void)didLoadTableViewMoreData:(PETableView*)tableView
{
    [self requestBooksWithOperation:RYCHTTPRequestModelOperation_Forward];
}

#pragma mark - notification
- (void)didReceiveNotification:(NSNotification *)notification
{
    if ([notification.name isEqualToString:FBLOADBOOKSNOTIFICATION]) {
        NSDictionary *userInfo = notification.userInfo;
        _catalogID = [userInfo objectForKey:@"catalogID"];
        self.title = [userInfo objectForKey:@"catalog"];
        [self requestBooksWithOperation:RYCHTTPRequestModelOperation_Refresh];
    }
}

#pragma mark - private
- (void)requestBooksWithOperation:(RYCHTTPRequestModelOperation)operation
{
    if (RYCHTTPRequestModelOperation_Normal == operation)
    {
        if (nil == _booksModel.allResponseList)
        {
            [self loadTableView:YES];
        }
        else
        {
            [self loadTableView:NO];
        }
        [self setupTableMoreView];
    }
    else if (RYCHTTPRequestModelOperation_Refresh == operation)
    {
        [self loadTableView:YES];
        [self setupTableMoreView];
    }
    
    _booksModel.catalogID = _catalogID;
    [_booksModel sendRequest:operation];
    [self showWaiting:NO];
}

- (void)setupTableMoreView
{
    if (_booksModel.hasNextPage) {
        [_tableView showTableMoreView];
    }
    else{
        [_tableView hideTableMoreView];
    }
}

- (void)loadTableView:(BOOL)isPullReloading
{
    if (_tableView == nil) {
        
        _tableView = [[PETableView alloc] initWithFrame:self.view.bounds];
        
        if (IOS_VERSION >= 7.0) {
            _tableView.frame = CGRectMake(0, 64, 320, 416);
        }
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.enabledPullRefresh = YES;
        _tableView.enabledLoadMoreData = YES;
        _tableView.separatorColor = [UIColor colorWithRed:150/255.0f green:161/255.0f blue:177/255.0f alpha:1.0f];
        _tableView.backgroundColor = [UIColor clearColor];
        
        [self.view addSubview:_tableView];
        
    }
    else{
        [_tableView reloadData];
    }
    
    if (isPullReloading)
    {
        if (NO == [_tableView isTableViewReloading])
        {
            [_tableView setTableViewIsReloading];
        }
    }
}

- (void)didHTTPRequestModelFinished:(RYCHTTPRequestModel *)aModel
{
    [super didHTTPRequestModelFinished:aModel];
    if (aModel == _booksModel) {
        _tableViewData = _booksModel.allResponseList;
        [self loadTableView:NO];
        if (RYCHTTPRequestModelOperation_Refresh == _booksModel.operation)
        {
            [_tableView reloadTableViewDataDone];
        }
        else if (RYCHTTPRequestModelOperation_Forward == _booksModel.operation)
        {
            [_tableView loadTableViewMoreDataDone];
        }
        
        [self setupTableMoreView];
        
    }
}

- (void)didHTTPRequestModelFailed:(RYCHTTPRequestModel *)aModel
{
    [super didHTTPRequestModelFailed:aModel];
    [_tableView reloadTableViewDataDone];
    [_tableView loadTableViewMoreDataDone];
    
}

@end
